package mygameserver;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Vector;

public class GameServer implements Runnable, Subject {

    private static final int PORT = 8189;
    private Socket client;
    private ServerSocket server;
    static Vector<Player> players = new Vector<Player>();
    ArrayList<Thread> threads = new ArrayList<Thread>();
    Thread servThread;
    private String listUpdate = "";

    public GameServer() {
        try {
            server = new ServerSocket(PORT);
            servThread = new Thread(this);
            servThread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (true) {
            try {
                client = server.accept();
                System.out.println("connection ID : " + client.hashCode());
                Thread t = new Thread(new ServerThread(client, this));
                t.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMessageTo(Socket s, String mess) {
        try {
            PrintWriter out = new PrintWriter(
                    new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
            out.println(mess);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("[to " + s.hashCode() + "] : " + mess);
    }

    public void kill() throws IOException {
        for (Thread t : threads) {
            t.stop();
        }
        for (Player p : players) {
            p.getcSocket().close();
        }
        servThread.stop();
    }

    @Override
    public void registerObserver(Observer o) {
        Player player = (Player) o;
        listUpdate = ".add;" + player.getpName() + ";" + player.getpHashCode() + ";";
        notifyObservers();
        players.add((Player) o);
    }

    @Override
    public void removeObserver(Observer o) {
        Player player = (Player) o;
        listUpdate = ".remove;" + player.getpName() + ";" + player.getpHashCode() + ";";
        players.remove(player);
        notifyObservers();
    }

    @Override
    public void notifyObservers() {
        for (Player p : players) {
            p.update(listUpdate);
        }
    }
}

